<template>
  <div class="check-item">
    <a-form-model layout="inline">
      <a-row
        v-for="(block, blockIndex) in blockItems"
        :key="blockIndex"
        class="check-item-block"
      >
        <h1 style="padding-left: 1rem">{{ blockIndex + 1 }}级审批</h1>
        <a-col
          :offset="2"
          v-for="(item, itemIndex) in block.nodeDetails"
          :key="`${blockIndex}-${itemIndex}`"
        >
          <a-form-model-item label="审批人">
            <a-cascader
              :options="departTree"
              placeholder="请选择"
              :disabled="actionType === 'preview'"
              change-on-select
              @change="(e, opt) => onOrgChange(e, blockIndex, itemIndex, opt)"
              @search="(e, opt) => onOrgSearch(e, blockIndex, itemIndex, opt)"
              v-model="blockItems[blockIndex].nodeDetails[itemIndex].range"
            />
          </a-form-model-item>
          <a-form-model-item>
            <a-select
              style="width: 120px"
              :disabled="actionType === 'preview'"
              v-model="
                blockItems[blockIndex].nodeDetails[itemIndex].approverRoleId
              "
              @change="(e, opt) => onRoleChange(e, blockIndex, itemIndex, opt)"
            >
              <a-select-option
                :value="item.value"
                v-for="item in optionGroup[blockIndex][itemIndex].role"
                :key="item.value"
                >{{ item.text }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
          <a-form-model-item>
            <a-select
              style="width: 120px"
              :disabled="actionType === 'preview'"
              @change="(e, opt) => onNameChange(e, blockIndex, itemIndex, opt)"
              v-model="blockItems[blockIndex].nodeDetails[itemIndex].approverId"
            >
              <a-select-option
                :value="item.value"
                v-for="item in optionGroup[blockIndex][itemIndex].user"
                :key="item.value"
                >{{ item.text }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
          <a-form-model-item>
            <a-icon
              v-if="actionType !== 'preview'"
              type="delete"
              @click="rowMins(blockIndex, itemIndex)"
            />
          </a-form-model-item>
        </a-col>
        <a-col :offset="2">
          <a-form-model-item>
            <a-button
              type="primary"
              icon="plus"
              v-if="actionType !== 'preview'"
              @click="rowPlus(blockIndex)"
            >
              添加
            </a-button>
          </a-form-model-item>
        </a-col>
        <a-col :offset="2">
          <a-form-model-item label="审批方式">
            <a-radio-group
              v-model="blockItems[blockIndex].approveType"
              :disabled="actionType === 'preview'"
            >
              <a-radio :value="100"> 会签 </a-radio>
              <a-radio :value="200"> 或签 </a-radio>
            </a-radio-group>
          </a-form-model-item>
        </a-col>
        <a-col :offset="2">
          <a-form-model-item label="回填标识">
            <a-select
              style="width: 120px"
              v-model="blockItems[blockIndex].callbackFlag"
              :disabled="actionType === 'preview'"
            >
              <a-select-option :value="1">是</a-select-option>
              <a-select-option :value="0">否</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <br />
      </a-row>
      <a-row
        class="check-item-block new-check-item"
        v-if="actionType !== 'preview'"
      >
        <a-col :offset="2" @click="blockPlus()"  class="cursor-pointer">
          <a-icon type="plus" />
          新建审批级别
        </a-col>
      </a-row>
      <a-row class="check-item-block new-check-item">
        <a-col :offset="2">
          <a-icon type="check-circle" theme="twoTone" /> 审批结束
        </a-col>
      </a-row>
      <div class="check-item-submit" v-if="actionType !== 'preview'">
        <a-space>
          <a-button type="danger" size="large" @click="checkFlowSubmit"
            >提交</a-button
          >
          <a-button size="large" @click="$router.go(-1)">取消</a-button>
        </a-space>
      </div>
    </a-form-model>
  </div>
</template>

<script>
import { cloneDeep } from 'lodash';
import { postApi } from '../../services/autoApi';
import { getDepartmentTree, getUserList } from '../../services/userManage';
import { getRoleList } from '../../services/roleManage';
import { DATA_CODE_SUCCESS, CODE_SUCCESS_UCENTER } from '../../utils/consts';

const rules = {};
const initCheckItem = {
  range: [],
  approverId: '',
  approverRoleId: '',
  approverDeptId: '',
  approverName: '',
  approverDeptName: '',
  approverRoleName: ''
};
const blockInput = {
  approveLevel: 1,
  approveType: 100,
  callbackFlag: 0,
  nodeName: 'defaultName'
};
const initOpt = {
  user: [],
  role: []
};
const isSubmited = false;
// 不是理想的版本
export default {
  name: 'checkItem',
  data() {
    return {
      rules,
      isSubmited,
      initOpt,
      departTree: [],
      checkItems: [],
      optionGroup: [[cloneDeep(initOpt)]],
      blockItems: [
        {
          nodeDetails: [cloneDeep(initCheckItem)],
          ...cloneDeep(blockInput)
        }
      ]
    };
  },
  props: {
    formModel: {
      type: Object,
      default: () => ({})
    },
    apiData: {
      type: Object,
      default: () => ({})
    },
    actionType: {
      type: String,
      default: () => 'add'
    }
  },

  // 这块需要优化
  // created() {
  // },
  methods: {
    rowPlus(b) {
      const item = cloneDeep(initCheckItem);
      const opt = cloneDeep(initOpt);
      (0, this.blockItems)[b].nodeDetails.push(item);
      (0, this.optionGroup)[b].push(opt);
    },
    rowMins(b, i) {
      (0, this.blockItems)[b].nodeDetails.splice(i, 1);
      (0, this.optionGroup)[b].splice(i, 1);
      // 如果是那一级别最后一条
      if (this.blockItems[b].nodeDetails.length === 0) {
        (0, this.blockItems).splice(b, 1);
        (0, this.optionGroup).splice(b, 1);
      }
    },
    formatCascader(data) {
      return Array.prototype.map.call(data || [], (item) => {
        if (item.children && Array.isArray(item.children)) {
          return {
            label: item.name,
            value: item.id,
            children: this.formatCascader(item?.children)
          };
        }
        return { label: item.name, value: item.id };
      });
    },
    onOrgChange(val, blockIndex, itemIndex, opt) {
      if (!val) return;
      const departmentId = val[val.length - 1];
      const { label } = opt[opt.length - 1];
      (0, this.blockItems)[blockIndex].nodeDetails[
        itemIndex
      ].approverDeptId = departmentId;

      (0, this.blockItems)[blockIndex].nodeDetails[
        itemIndex
      ].approverDeptName = label;

      (0, this.blockItems)[blockIndex].nodeDetails[itemIndex].approverRoleId =
        '';

      (0, this.blockItems)[blockIndex].nodeDetails[itemIndex].approverId = '';

      this.setRoleSelect(departmentId, blockIndex, itemIndex);
    },
    onRoleChange(val, blockIndex, itemIndex) {
      const selectedText = (0, this.optionGroup)[blockIndex][
        itemIndex
      ].role.filter((item) => item.value === val)[0].text;
      (0, this.blockItems)[blockIndex].nodeDetails[
        itemIndex
      ].approverRoleName = selectedText;
      (0, this.blockItems)[blockIndex].nodeDetails[itemIndex].approverId = '';
      this.setUserSelect(val, blockIndex, itemIndex);
    },
    blockPlus() {
      this.optionGroup.push([cloneDeep(this.initOpt)]);
      this.blockItems.push({
        nodeDetails: [cloneDeep(initCheckItem)],
        ...cloneDeep(blockInput)
      });
      // 设置审批等级
      (0, this.blockItems)[
        this.blockItems.length - 1
      ].approveLevel = this.blockItems.length;
    },
    blockMins(i) {
      this.checkItems.splice(i, 1);
    },
    checkFlowSubmit() {
      if (this.isSubmited) return;
      this.$emit('inputPanelValidate');
      if (!this.formModel.approveConfigName) return;
      this.isSubmited = true;
      const { businessFlowSubId, businessFlowId, id } = this.$route.query;
      const { approveConfigName } = this.formModel;
      const params = {
        businessFlowSubId,
        businessFlowId,
        nodeList: this.blockItems,
        approveConfigName,
        id
      };
      // 这里的api需要统一管理
      postApi('/approve/approveConfig', params).then((res) => {
        const { code, message } = res.data;
        if (code === DATA_CODE_SUCCESS) {
          this.$message.success(message);
          this.$router.go(-1);
        } else {
          this.isSubmited = false;
          this.$message.error(message);
        }
      });
    },
    initOrgSelect() {
      getDepartmentTree().then((res) => {
        const { code, message, data } = res.data;
        if (code === 200) {
          this.departTree = this.formatCascader(data.departmentList);
          return;
        }
        if (code !== 11005) {
          this.$message.error(message);
        }
      });
    },
    setRoleSelect(departmentId, blockIndex, itemIndex) {
      // if ((0, this.optionGroup)[blockIndex][itemIndex].role.length > 0) return;
      const params = { departmentId, pageSize: 5000, currentPage: 1 };

      getRoleList(params).then((res) => {
        const { code, message, data } = res.data;
        if (code === CODE_SUCCESS_UCENTER) {
          const userOpt = data.roleList.map((item) => ({
            departmentId,
            text: item.name,
            value: item.id
          }));
          this.optionGroup[blockIndex][itemIndex].role = cloneDeep(userOpt);
          return;
        }
        this.$message.error(message);
      });
    },
    setUserSelect(val, blockIndex, itemIndex) {
      // if ((0, this.optionGroup)[blockIndex][itemIndex].user.length > 0) return;
      const { range } = (0, this.blockItems)[blockIndex].nodeDetails[itemIndex];
      const departmentId = range[range.length - 1];
      const roleId = val;
      const params = {
        departmentId,
        roleId,
        pageSize: 5000,
        currentPage: 1
      };
      getUserList(params).then((res) => {
        const { code, message, data } = res.data;
        if (code === CODE_SUCCESS_UCENTER) {
          const userOpt = Array.prototype.map.call(
            data.users || [],
            (item) => ({
              departmentId,
              text: item.username,
              value: item.openId
            })
          );
          (0, this.optionGroup)[blockIndex][itemIndex].user = userOpt;
          return;
        }
        this.$message.error(message);
      });
    },
    inputPanelValidate() {
      this.$emit('inputPanelValidate');
    },
    getSelectLabel() {},
    // 反筛出babel;这里没有用啦~~~
    getCascaderLabel(val) {
      let init = this.departTree;
      val.forEach((v) => {
        [init] = init.filter((item) => item.value === v);
        if (init?.children?.length > 0) {
          init = init.children;
        }
      });
      return init;
    },
    onNameChange(val, blockIndex, itemIndex) {
      const selectedText = (0, this.optionGroup)[blockIndex][
        itemIndex
      ].user.filter((item) => item.value === val)[0].text;
      (0, this.blockItems)[blockIndex].nodeDetails[
        itemIndex
      ].approverName = selectedText;
    },
    resetFlowField() {
      this.blockItems = [
        {
          nodeDetails: [cloneDeep(initCheckItem)],
          ...cloneDeep(blockInput)
        }
      ];
      this.optionGroup = [[cloneDeep(initOpt)]];
    }
  },
  watch: {
    apiData(val) {
      this.initOrgSelect();
      this.isSubmited = false;
      if (val.nodeList) {
        this.optionGroup = [];
        const { nodeList } = val;
        nodeList.forEach((blockItem, blockIndex) => {
          const { nodeDetails } = blockItem;
          this.optionGroup.push([]);
          nodeDetails.forEach((item, itemIndex) => {
            // 这里是为了响应式做的处理 与注释中的处理效果相同 role 与 user 需要是响应式的
            this.optionGroup[blockIndex].push(cloneDeep(this.initOpt));
            this.optionGroup[blockIndex][itemIndex].user = [
              { text: item.approverName, value: item.approverId }
            ];
            this.optionGroup[blockIndex][itemIndex].role = [
              { text: item.approverRoleName, value: item.approverRoleId }
            ];
          });
        });
        this.blockItems = cloneDeep(nodeList);
      }
    },
    getSelectLabel() {},
    // 反筛出babel;这里没有用啦~~~
    getCascaderLabel(val) {
      let init = this.departTree;
      val.forEach((v) => {
        [init] = init.filter((item) => item.value === v);
        if (init?.children?.length > 0) {
          init = init.children;
        }
      });
      return init;
    },
    onNameChange(val, blockIndex, itemIndex) {
      const selectedText = (0, this.optionGroup)[blockIndex][
        itemIndex
      ].user.filter((item) => item.value === val)[0].text;
      (0, this.blockItems)[blockIndex].nodeDetails[
        itemIndex
      ].approverName = selectedText;
    }
  }
};
</script>

<style lang="less" scoped>
.check-item {
  padding-bottom: 1rem;
  .check-item-block {
    box-shadow: 0px 0px 2px grey;
    border-radius: 0.1rem;
    margin-top: 36px;
    padding-top: 0.5rem;
  }
  // .check-item-block:not(:nth-last-child(2)):after {
  //   content: "↓";
  //   display: block;
  //   font-size: 36px;
  //   position: absolute;
  //   bottom: -36px;
  //   left: 20rem;
  // }
  .new-check-item {
    padding: 1rem 0;
  }
}
.block-add {
  margin-top: 2rem;
}
.check-item-submit {
  display: flex;
  justify-content: center;
  text-align: center;
  margin-top: 36px;
}
.cursor-pointer {
  cursor: pointer;
}
</style>
